<template>
  <div class="app-container">
    <div class="action-container">
      <el-button type="primary" @click="handleCreateOrgEvent">增加<i class="el-icon--right" /></el-button>
    </div>
    <div class="filter-container">
      <el-select v-model="listQuery.f_eq_parentId" style="width: 120px" class="filter-item" placeholder="上级单位" @change="onParentIdChanged">
        <el-option label="上级单位" value="" />
        <el-option v-for="item in parentOrgList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.f_eq_type" style="width: 120px" class="filter-item" placeholder="类别" @change="handleFilter">
        <el-option v-for="item in typeOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="listQuery.f_lk_name" style="width: 200px;" class="filter-item" placeholder="名称" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="resetFiler">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="list" element-loading-text="数据正在加载中，请稍后..." border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="单位名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上级单位">
        <template slot-scope="scope">
          <span>{{ (scope.row.parent || {}).name || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="类别" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type | typeValueFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间">
        <template slot-scope="scope">
          <span>{{ scope.row.modifyTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button type="success" size="small" @click="handleUpdateOrgEvent(scope.row)">修改<i class="el-icon--right" /></el-button>
          <el-button type="danger" size="small" @click="handleDeleteOrgEvent(scope.row.id)">删除<i class="el-icon--right" /></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="org" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="ID" prop="type">
          <span>{{ org.id }}</span>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="org.name" />
        </el-form-item>
        <el-form-item label="上级单位" prop="parentId">
          <el-select v-model="org.parentId" class="filter-item" placeholder="">
            <el-option label="无" :value="0" />
            <el-option v-for="item in parentOrgList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="地址" prop="title">
          <el-input v-model="device.address"></el-input>
        </el-form-item>
-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="tryCreateOrg">确定</el-button>
        <el-button v-else type="primary" @click="tryUpdateOrg">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox } from 'element-ui'
import { getOrgList, createOrg, updateOrg, deleteOrg } from '@/api/org'

const typeOptions = [
  { label: '全部' },
  { key: '1', label: '一级单位' },
  { key: '2', label: '二级单位' }
]

export default {
  filters: {
    typeValueFilter(status) {
      const statusMap = {
        1: '一级单位',
        2: '二级单位',
        3: '三级单位'
      }
      return statusMap[status]
    },
    statusClassFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    },
    statusValueFilter(status) {
      const statusMap = {
        0: '锁定',
        1: '正常'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: null,
      listQuery: {
        page: 1,
        size: 20,
        f_eq_parentId: undefined,
        f_lk_name: undefined,
        f_eq_type: undefined
      },
      typeOptions: typeOptions,
      org: {
        id: 0,
        name: '',
        parentId: 0
      },
      parentOrgList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '增加',
        update: '修改'
      },
      rules: {
        name: [{ required: true, message: '名称不能为空。', trigger: 'change' }],
        parentId: [{ required: true, message: '上级单位不能为空。', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchParentOrgList()
    this.fetchData()
  },
  methods: {
    fetchParentOrgList() {
      getOrgList({ 'f_eq_parentId': '0' }).then(response => {
        this.parentOrgList = response.data
      })
    },
    fetchData() {
      this.listLoading = true
      getOrgList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    onParentIdChanged() {
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetFiler() {
      this.listQuery = {}
      this.listQuery.page = 1
      this.listQuery.size = 20
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleCreateOrgEvent() {
      // 更新上级单位数据
      this.fetchParentOrgList()

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryCreateOrg() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createOrg(this.org).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleUpdateOrgEvent(row) {
      // 更新上级单位数据
      this.fetchParentOrgList()

      const t = Object.assign({}, row) // copy obj
      this.org.id = t.id
      this.org.name = t.name
      this.org.parentId = t.parentId

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryUpdateOrg() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const row = Object.assign({}, this.org)
          updateOrg(row).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleDeleteOrgEvent(id) {
      MessageBox.confirm('请确认是否要删除该单位？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          deleteOrg(id).then(() => {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {})
    }
  }
}
</script>
